var cfg = require('../../utils/cfg');
// var socketUtil = require('../../utils/socketUtil');

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    joinCount : 1,
    timeWaitFun: {},
    count : 0,
    waitPic: '/images/wait1.png',
    waitText : '等待中...',
    modelType: 1,
    showStart: '.hide',
    joinUsers : []

  },

  waitUser: function () {
    let that = this;
    that.data.timeWaitFun = setInterval(function () {
      console.log('>>>>>wait...' + that.data.count);
      let waitPic = that.data.count % 2 == 0 ? '/images/wait1.png' : '/images/wait2.png';
      let waitText = that.data.count % 2 == 0 ? '等待中...' : '等待中. .';
      that.data.count += 1;
      that.setData({ waitPic: waitPic });
      that.setData({ waitText: waitText });
    }, 1000);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _self = this;
    _self.setData({
      userInfo: app.globalData.userInfo
    })
    
  },

  startPlay: function () {
    let that = this;
    if (that.data.joinCount < 2) {
      wx.showToast({
        title: '至少有两人参与',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    wx.request({
      url: cfg.host + cfg.mwurl.startPlay,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        roomTicket: wx.getStorageSync('roomTicket'),
        offset: wx.getStorageSync('paperOffset')
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.code != 1000) {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })

          return;
        }

        let offset = wx.getStorageSync('paperOffset');
        wx.setStorageSync('paperOffset', offset + 1);

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  createRoom: function () {
    let that = this;
    wx.request({
      url: cfg.host + cfg.mwurl.createRoom,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        nickName: app.globalData.userInfo.nickName,
        picUrl: app.globalData.userInfo.avatarUrl,
        roomTicket: wx.getStorageSync('roomTicket'),
        model: that.data.modelType
      },
      success: function (res) {
        console.log(res.data);
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.createRoom();
    this.waitUser();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //注册回调函数
    // socketUtil.registCallBack(this.doSocket);
    app.globalData.socketCallBack = this.doSocket;
  },

  doSocket: function (res) {
    console.log('ready socket ' + res);
    let that = this;
    let wsDTO = res

    if (1001 === wsDTO.wsType) {
      clearInterval(this.data.timeWaitFun);
      let userInfo = wsDTO.data;
      let joinUsers = that.data.joinUsers;
      let joinCount = that.data.joinCount;
      
      for (let i=0; i<joinUsers.length; i++) {
        if (joinUsers[i].openId == userInfo.openId) {
          console.log("用户重复参与" + userInfo.openId);
          return;
        }
      }

      joinUsers.push(userInfo);

      that.setData({ joinUsers: joinUsers, joinCount: joinCount + 1, showStart: '.show' });
    }

    if (1002 === wsDTO.wsType) {
      //获取答卷数据

      wx.setStorageSync('paperInfo', wsDTO);
      wx.reLaunch({
        url: '/pages/paper/paper?fromType=12&&model=1'
      })
    }

    if (1004 === wsDTO.wsType) {
      clearInterval(this.data.timeWaitFun);
      let userInfo = wsDTO.data;
      let joinUsers = that.data.joinUsers;
      let joinCount = that.data.joinCount;

      for (let i = 0; i < joinUsers.length; i++) {
        if (joinUsers[i].openId == userInfo.openId) {
          console.log("用户离开房间" + userInfo.openId);
          if (joinCount > 1) {
            joinCount -= 1;
          }

          joinUsers.splice(i, 1);
        }
      }

      that.setData({ joinUsers: joinUsers, joinCount: joinCount, showStart: '.show' });
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('ready onUnload');
    clearInterval(this.data.timeWaitFun);
  },

  leaveRoom2: function () {
    let that = this;
    wx.request({
      url: cfg.host + cfg.mwurl.leaveRoom,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        roomTicket: wx.getStorageSync('roomTicket')
      },
      success: function (res) {
        console.log(res.data);
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  leaveRoom: function () {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定离开房间？',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: cfg.host + cfg.mwurl.leaveRoom,
            data: {
              openId: wx.getStorageSync('loginUser').openId,
              roomTicket: wx.getStorageSync('roomTicket')
            },
            success: function (res) {
              console.log(res.data);
              wx.reLaunch({
                url: '/pages/home/home',
                success: function () {
                  console.log('跳转到home页面');
                }
              });
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            method: 'POST'
          })
        } else if (res.cancel) {

        }
      }
    })

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})